<template>
  <el-menu
      background-color="whitesmoke"
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      :ellipsis="false"
      @select="handleSelect"
  >

    <el-input v-if="c.value==null" v-model="c.title" style="text: relative;top: 0px;font-size: large" placeholder="请输入文章标题..."></el-input>
    <el-input v-else v-model="c.title" style="text: relative;top: 0px;font-size: large" :placeholder="c.title"></el-input>
    <div class="flex-grow"/>
    <el-menu-item >
      <el-button type="danger" plain @click="handleClick=true">解锁</el-button>
      <el-dialog  v-model="handleClick" title="解锁ai编辑器"  >
        <template #default>
          您需要花费100篝火币解锁30天ai编辑器吗？
        </template>
        <template #footer>
          <div  class="dialog-footer">
            <el-button @click="handleClick = false" style="position: relative; right: 30px">取消</el-button>

              <el-button type="primary" @click="editorPay">
                确定
              </el-button>

          </div>

        </template>

      </el-dialog>
    </el-menu-item>
    <el-menu-item >
      <el-button type="primary" plain @click="pushdata()">草稿箱</el-button>
    </el-menu-item>
    <el-menu-item class="popover-item">

      <!--弹出框开始      -->
      <el-popover
          :visible="visible"
          placement="bottom"
          :width="700"
          trigger="click"
          content="this is content, this is content, this is content"
          el-menu-demo
          class="el-popover__popper"
          z-index="0.1"
          style="position: relative"
      >
        <template #reference>
          <el-button type="primary" @click="visible=true">发布</el-button>
        </template>
        <div style="font-size: 20px;margin-left: 5px;color: #1D2129">发布文章</div>
        <span class='underline'></span>

        <!--分类按钮开始      -->

        <div style="margin-top: 20px; display: flex; flex-wrap: wrap;">
          <span style="margin-left: 105px; font-size: 15px;color: #1D2129">
            <span style="color: red;">*</span>分类:</span>
          <el-cascader :options="categoryArr" :show-all-levels="false" style="margin-left: 5px" @change="handleChange"/>
          <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 25px ; /* 调整下划线与标题的间距 */"> </span>
          <!--分类按钮开始      -->
          <!-- 添加标签开始       -->
          <span style="margin:5px 0 0 75px;font-size: 15px;color: #1D2129">
          <span style="color: red;">*</span>添加标签:</span>
          <el-form-item style="z-index: 100;">
            <div class="tag-input">

              <el-checkbox v-for="item in TagList" v-model="selectTags" :label="item.id" size="large" style="margin-left: 10px; ">
                {{item.tagName}}
              </el-checkbox>

<!--              <a-select  class="popover-select" mode="tags" style="width: 250px ; "-->
<!--                        placeholder="请输入标签(限制长度为1-12)"-->
<!--                        @change="handleChangeTag" size="large" :max-tag-count="5" v-model="selectTags"-->
<!--                        :dropdown-style="{ maxHeight: '170px', overflowY: 'auto' ,}"  >-->
<!--                <a-select-option v-for="item in TagList" :key="item.id"-->
<!--                                 v-infinite-scroll="load" style="position: absolute;right: -5px;" >-->
<!--                  {{ item.tagName }}-->
<!--                </a-select-option>-->
<!--              </a-select>-->
            </div>
          </el-form-item>
          <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
          <!-- 添加标签结束       -->
          <!--上传图片开始        -->
          <span style="margin:5px 0 0 85px;font-size: 15px;color: #1D2129">文章封面:</span>
          <el-upload
              v-model:file-list="fileList"
              action="http://123.60.129.240:49380/upload/uploadImage"
              name="file"
              limit="1"
              style="margin-left: 5px;"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image"/>
          </el-dialog>
          <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
          <!--上传图片结束       -->
          <!--编辑摘要开始   -->
          <span style="margin:5px 0 0 75px;font-size: 15px;color: #1D2129">编辑摘要:</span>
          <el-input
              v-model="c.brief"
              :autosize="{ minRows: 6 }"
              maxlength="100"
              placeholder="前100字为摘要"
              show-word-limit
              type="textarea"
              style="width: 500px;margin-left: 5px"
          />
          <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
          <!--选择公开私密开始-->
          <span style="margin:5px 0 0 75px;font-size: 15px;color: #1D2129">
          <span style="color: red;">*</span>选择状态:</span>
          <el-radio-group v-model="c.isDisplay" style="margin-left: 5px">
            <el-radio :label="0">私密</el-radio>
            <el-radio :label="1">公开</el-radio>
<!--            <el-radio :label="2">付费解锁</el-radio>-->
          </el-radio-group>
          <!--选择公开私密结束-->
          <span style=" border-bottom: 1px solid #ccc; /* 将下划线颜色设置为灰色 */
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
          <!--编辑摘要结束     -->

          <!--取消与确认发布按钮开始     -->
          <div style="display: flex; justify-content: center;">
            <el-button type="primary" @click="savedraft()" >保存草稿</el-button>
            <el-button style="margin-left: 370px;width: 100px" @click="visible = false">取消</el-button>
            <el-button type="primary" style="margin-left: 20px" @click="post()" >确认与发布</el-button>
          </div>
          <!--取消与确认发布按钮结束     -->
        </div>
      </el-popover>

    </el-menu-item>
    <el-menu-item>

      <el-button style="font-size: 20px;height: 55px"
                 text @click="outerVisible = true" >
        <el-menu-item>
          <el-icon size="30"><Switch /></el-icon>
        </el-menu-item>
      </el-button>
    </el-menu-item>
    <el-avatar
        :size="50"
        src="../gh.webp"
        @click="pushIndex"
    />
  </el-menu>

  <div ref="editorContent" class="editor-content" ></div>

  <el-dialog v-model="outerVisible" title="切换为markdown编辑器">
    <template #default>
      切换写作模式后，当前内容不会迁移，但会自动保存为草稿。
      <el-dialog
          style="width: 100%;height: 100%"
          v-model="innerVisible"
          width="100%"
          title="Inner Dialog"
          append-to-body
      />
    </template>
    <template #footer>
      <div  class="dialog-footer">
        <el-button @click="outerVisible = false" style="position: relative; right: 30px">取消</el-button>
        <router-link to="/text2" >
          <el-button type="primary">
            确定
          </el-button>
        </router-link>
      </div>

    </template>

  </el-dialog>

</template>

<script setup>

import {onMounted, ref} from "vue";
import Editor from 'wangeditor';
import {ElMessage} from 'element-plus'
import axios from "axios";
import router from "@/router";
import tokenAxios from "@/http/request/TokenAxios";

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])

const c = ref({title: "",brief:"",isDisplay:0,draft:0,detail:"",editortype:0});

const categoryArr=ref([]);

const selectTags = ref([])
const TagList = ref([])
const page = ref(0)

//


//标签-------------
const handleChangeTag = (value) => {
  // 从 TagList 中匹配用户输入的标签，获取对应的标签ID组成数组
  c.value.tagList=TagList.value.filter(tag=>value.includes(tag.id)).map(tag=>tag.id);

};

const load = () => {

  // if (TagList.value.length > 0 && TagList.value.length % 12 !== 0) {
  //   return;
  // }

  page.value++;
  tokenAxios.get('http://123.60.129.240:49282/tag?page=' + page.value)
      .then((response) => {
        if (response.state === 20000) {
          if (response.data.list.length === 0) {
            // 数据库中没有更多数据了，停止发送请求
            return;
          }
          TagList.value = response.data.list;
        } else {
          ElMessage.error(response.message)
        }
      })
}

const handleChange = (value)=> {
  // value就是选中的值
  // 您可以在这里将value赋值给c的上传参数
  // console.log(typeof value)
  c.value.categoryId=parseInt(value[value.length - 1]);
}


const loadCategories = ()=>{
  tokenAxios.get(BASE_URL+':49282/categories/tree')
      .then((response)=>{
        if (response.state===20000){
          categoryArr.value=response.data;
        }
      })
}

  const loadDraft =(articleId)=>{
    console.log(articleId)
    console.log(getUser().id)
    tokenAxios.get(BASE_URL+':49282/article/selectDraftDetail/'+getUser().id+'/'+articleId)
        .then((response)=>{
      if (response.state===20000){
        c.value=response.data;
        if (editor) {
          editor.txt.html(c.value.detail);
        }
      }

    })
  }



//上传图片开始-----------
const handleSuccess = (response, file, fileList) => {
//response = JsonResult
  //判断上传的文件是图片还是视频
  if (file.raw.type.includes('image')) {
    //把上传成功的图片路径装进内容对象c里面
    c.value.coverUrl = response.data;
  } else {
    // 如果上传的不是图片路径，返回错误提示
    ElMessage.error('上传的文件类型不正确!');
    return;
  }
}
const handleRemove = (uploadFile, uploadFiles) => {
  if (uploadFile.raw.type.includes('image')) {
    // 把上传成功的图片路径装进内容对象c里面
    c.value.imgUrl = null;
    console.log(uploadFile.response.data);
    // 发出删除文件的请求
    let url = uploadFile.response.data; // 得到当前文件的路径
    axios.post(BASE_URL+':49380/upload/deleteImage?url=' + url).then((response) => {
      if (response.data.state == 20000) {
        ElMessage.success("删除文件完成!");
      }
    })
  }
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
//上传图片结束-----------



let textarea = ref('')
const post = () => {
  if (c.value.title.trim() == '') {
    ElMessage.error('标题不能为空!');
    return;
  }

//把富文本编辑器里面的内容取出   取出的是包含html标签的内容
  c.value.detail = editor.txt.html();
//设置摘要 (正文的前30个字符作为摘要)   editor.txt.text()得到纯文本内容(不包括标签)
  c.value.brief = editor.txt.text().slice(0, 30);
  tokenAxios.post(BASE_URL+':49282/article/add-new', c.value)
      .then((response) => {
        if (response.state == 20000) {
          ElMessage.success("发布完成!");
          router.push('/creation/banner');//跳转到文章管理页面
        }else {
          ElMessage.error(response.message)
        }
      })
}

const savedraft= ()=> {
  //把富文本编辑器里面的内容取出   取出的是包含html标签的内容
  c.value.detail = editor.txt.html();
//设置摘要 (正文的前30个字符作为摘要)   editor.txt.text()得到纯文本内容(不包括标签)
  c.value.brief = editor.txt.text().slice(0, 30);
  c.value.draft=1;
  c.value.editortype=0;
  tokenAxios.post(BASE_URL+':49282/article/add-new', c.value)
      .then((response) => {
        if (response.state == 20000) {
          ElMessage.success("发布完成!");
          router.push('/creation/banner');//跳转到文章管理页面
        }else {
          ElMessage.error(response.message)
        }
      })
}

const editorPayParam = ref({price:30,hours:720})
const editorPay=()=>{
  tokenAxios.post(BASE_URL + ':49283/reward/editorPay',editorPayParam.value).then((response)=>{
    if (response.state === 20000){
      ElMessage.success("解锁成功!");
      router.push('/text2');
    }else {
      ElMessage.error(response.message);
    }
  })
}

const handleClick=ref(false)
//编辑器和文章摘要
const editorContent = ref(null);
let editor = null;
onMounted(() => {
  editor = new Editor(editorContent.value);
  editor.config.placeholder = "请输入内容详情..."
  let id = new URLSearchParams(location.search).get('id');
  if (id!=null){
    loadDraft(id);
  }
  loadCategories();
  load();



  editor.create();


})


const outerVisible = ref(false)
const innerVisible = ref(false)
const visible = ref(false)


const pushIndex = () => {
  router.push('/index')
}

const pushdata = () => {
  router.push('/creation/data')
}
</script>

<style scoped>


.flex-grow {
  flex-grow: 2;
}



.el-popover__popper {
  z-index: 1000;
  position: relative;
  overflow: visible;
}


.editor-content {
  position: relative;
  z-index: 5; /* 为 onMounted 中创建的内容设置较低的 z-index 值 */
}
.popover-select .ant-select-dropdown {
  z-index: 1001 !important;
}
.popover-select {
  /* 确保选择器可滚动 */
  max-height: 200px; /* 根据实际情况设置合适的最大高度 */
  overflow-y: auto;

  /* 调整定位以确保其在弹出框内可见 */
  position: relative;
  z-index: inherit;
}
.underline {
  border-bottom: 1px solid #ccc; /* 将下划线颜色设置为灰色 */
  display: inline-block; /* 使下划线占据一行 */
  width: 100%; /* 下划线宽度 */
  margin: 5px; /* 调整下划线与标题的间距 */

}


</style>